package com.kmist.xiakexing.presenters;

import android.util.Log;

import com.kmist.xiakexing.interfaces.INpcCallback;
import com.kmist.xiakexing.interfaces.INpcPresenter;
import com.kmist.xiakexing.main.socket.DataRecver;
import com.kmist.xiakexing.main.socket.DataSender;
import com.kmist.xiakexing.main.socket.ISocketCallback;
import com.kmist.xiakexing.main.socket.SockPresenter;
import com.kmist.xiakexing.main.socket.cmd;

import com.kmist.xiakexing.main.socket.retCode;
import com.kmist.xiakexing.tools.Chinesed;
import com.kmist.xiakexing.tools.Config;
import com.kmist.xiakexing.utils.cmds.Look;
import com.kmist.xiakexing.utils.scene.NpcBean;
import com.kmist.xiakexing.utils.scene.PlayerBean;
import com.kmist.xiakexing.utils.scene.PlayerTaskBean;
import com.kmist.xiakexing.utils.scene.TaskBean;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class NpcPresenter implements INpcPresenter, ISocketCallback {
    private static final String TAG = "NPC";
    private static NpcPresenter sInstance = null;
    private static TaskPresenter taskPresenter;
    private static PlayerPresenter playerPresenter;
    private final SockPresenter sockPresenter;

    INpcCallback callback;
    private NpcBean curNpc;

    public NpcPresenter() {
        sockPresenter = SockPresenter.getInstance();
        sockPresenter.setCallback(this);
        taskPresenter = TaskPresenter.getInstance();
        playerPresenter = PlayerPresenter.getInstance();
    }

    public static NpcPresenter getsInstance() {
        if(sInstance == null){
            synchronized (NpcPresenter.class){
                sInstance = new NpcPresenter();
            }
        }
        return sInstance;
    }

    @Override
    public void addNpc(NpcBean npcBean) {

    }

    @Override
    public void addNpcList(List<NpcBean> npcBeans) {

    }

    @Override
    public void delNpc(NpcBean npcBean) {

    }

    /**
     * 获取当前npc详细信息
     * @param npc
     */
    @Override
    public void getNpcMoreInfo(NpcBean npc) {
        curNpc = npc;
        JSONObject json = Config.val2json("id", npc.getId());
        DataSender info = new DataSender(cmd.CMD_NPC_GETNPCMOREINFO, json.toString());
        sockPresenter.sendMessage(info.toString());
    }

    @Override
    public void getNpcList(String NpcArray) {

        if(NpcArray != null){
            String str = "{\"npc\":" + NpcArray + "}";
            DataSender info = new DataSender(cmd.CMD_NPC_GETNPCLIST, str);
            sockPresenter.sendMessage(info.toString());
        }
    }

    @Override
    public void getNpcTask(String npcTask) {
        TaskPresenter taskPresenter = TaskPresenter.getInstance();
        taskPresenter.getTask(npcTask);
    }

    /**
     * 处理npc的greeting
     * @param npc
     * @param player
     * @return
     */
    @Override
    public String getGreeting(NpcBean npc, PlayerBean player) {
        String greet = "";

        try {
            JSONArray greetArray = new JSONArray(npc.getGreet());
            for(int i = 0 ; i < greetArray.length(); i++){
                greet += greetArray.getString(i);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return greet;
    }

    @Override
    public NpcBean getNpcd() {
        return curNpc;
    }


    @Override
    public void registerViewCallback(INpcCallback callback) {
        this.callback = callback;
    }

    @Override
    public void unRegisterViewCallback(INpcCallback callback) {

    }

    @Override
    public void onConnected() {
        //todo sock
    }

    @Override
    public void onNetworkError() {
        //todo sock
    }

    @Override
    public void onDataRecved(DataRecver dataRecver) {

        if (!dataRecver.getResp_cmd().substring(0,2).equals(cmd.CMD_NPC)) {
            return;
        }

        switch (dataRecver.getResp_code()){

            case retCode.RET_OK:{
                if(dataRecver.getResp_cmd().equals(cmd.CMD_NPC_GETNPCLIST)){
                    getNpc_handler(dataRecver);
                }else if(dataRecver.getResp_cmd().equals(cmd.CMD_NPC_GETNPCMOREINFO)){
                    getNpcMoreInfo_handler(dataRecver);
                }else{
                    Log.d("RECV:"," 操作成功！");
                }
            } break;
            case retCode.RET_NONE: /* do nothing ,but success */
                callback.onNpcLoadEmpty();
                break;
            default:
                Log.d("RECV:","cmd exe ERROR: "+dataRecver.getResp_code());
                break;
        }
    }

    private void getNpcMoreInfo_handler(DataRecver dataRecver) {
        if(parseNpcMoreInfo(dataRecver.getResp_data(), curNpc)){
            callback.onNpcLoaded(curNpc);
        }else{
            callback.onNpcLoadError();
        }

    }

    private boolean parseNpcMoreInfo(String resp_data, NpcBean curNpc) {
        try{
            JSONObject root = new JSONObject(resp_data);
            JSONObject jnpc = root.getJSONObject("npc");
            curNpc.setTitle(jnpc.getString("title"));

            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private void getNpc_handler(DataRecver dataRecver) {
        List<NpcBean> NpcList = new ArrayList<>();

        if(parseNpcMsg(dataRecver.getResp_data(), NpcList)){
            callback.onNpcsLoaded(NpcList);
        }else{
            callback.onNpcLoadError();
        }
    }

    private boolean parseNpcMsg(String resp_data, List<NpcBean> npcList) {

        try {
            JSONObject jroot = new JSONObject(resp_data);
            JSONArray list = jroot.getJSONArray("npclist");

            for(int i =0; i < list.length(); i++){
                JSONObject value = list.getJSONObject(i);

                NpcBean tmp = new NpcBean();
                tmp.setId(value.getInt("id"));
                tmp.setName(value.getString("name"));
                tmp.setGender(value.getString("gender"));
                tmp.setAge(value.getInt("age"));
                tmp.setDesc(value.getString("info"));
                tmp.setCombat_exp(value.getInt("combat_exp"));
                tmp.setTaskIds(value.getString("task_id"));
                tmp.setGreet(value.getString("greeting"));

                if(!tmp.getTaskIds().equals("0"))
                {
                    /* parse npc`s task */
                    JSONArray task = new JSONArray(tmp.getTaskIds());
                    List<TaskBean> tasklist = new ArrayList<>();
                    for(int j = 0; j < task.length(); j++){
                        JSONObject taskNode = task.getJSONObject(j);

                        TaskBean tasktmp = new TaskBean();
                        tasktmp.setTaskId(taskNode.getInt("id"));
                        tasktmp.setTaskName(taskNode.getString("name"));
                        tasktmp.setTaskLeixing(taskNode.getInt("lx"));
                        tasklist.add(tasktmp);
                    }

                    tmp.setNpcTaskList(tasklist);
                }

                npcList.add(tmp);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
